package com.lhj.bootdemo.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

public class DownLoadFileUtil {

    /**
     * 文件下载
     *
     * @param response
     * @param filePath
     * @param fileName
     * @throws Exception
     */
    public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String filePath, String fileName) throws Exception {
        File file = new File(filePath);
        FileInputStream in = new FileInputStream(file);
        OutputStream out = response.getOutputStream();
        //防止在火狐浏览器中下载的文件名称中文乱码
        final String userAgent = request.getHeader("USER-AGENT");
        if (userAgent.contains("Mozilla")) {
            fileName = new String(fileName.getBytes(), "ISO8859-1");
        } else {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }
        if (file.exists()) {
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            response.setContentType("application/octet-stream");
            byte buffer[] = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            in.close();
            out.close();
        }
    }

}
